package com.jade.store.wechat.biz.service;

import com.jade.store.wechat.biz.common.Configure;
import com.jade.store.wechat.biz.common.aes.WXBizMsgCrypt;
import com.jade.store.wechat.biz.protocol.WechatAppAutoPush;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;

/**
 * Created with IntelliJ IDEA.
 * User: jinya
 * Date: 2016/12/20
 * Time: 13:16
 * TEL :17701640710   MAIL:2009_jinya@163.com
 * To change this template use File | Settings | File Templates.
 */
public class WxAppPushService {
    /**
     * 1.获取推送component_verify_ticket协议
     * 在公众号第三方平台创建审核通过后，微信服务器会向其“授权事件接收URL”每隔10分钟定时推送component_verify_ticket。
     * 第三方平台方在收到ticket推送后也需进行解密（详细请见【消息加解密接入指引】），接收到后必须直接返回字符串success。
     * @param request
     * @throws Exception
     */
    public static WechatAppAutoPush getReceiveauthcode(HttpServletRequest request)
            throws Exception
    {
        String msgSignature = request.getParameter("msg_signature");
        String timeStamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");

        WXBizMsgCrypt pc = new WXBizMsgCrypt(Configure.token, Configure.key,  Configure.appID);
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line = null;
        while ((line=br.readLine()) != null) {
            sb = sb.append(line);
        }
        String postData = sb.toString();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(postData);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Encrypt");
            NodeList nodelist2 = root.getElementsByTagName("MsgSignature");
            String encrypt = nodelist1.item(0).getTextContent();

            String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
            String fromXML = String.format(format, encrypt);
            /**
             * 构造函数
             *
             * @param token
             *            公众平台上，开发者设置的token
             * @param encodingAesKey
             *            公众平台上，开发者设置的EncodingAESKey
             * @param appId
             *            公众平台appid
             *
             * @throws AesException
             *             执行失败，请查看该异常的错误码和具体的错误信息
             */
            String result = pc.decryptMsg(msgSignature, timeStamp, nonce, fromXML);
            System.out.println(result + ".................");
            WechatAppAutoPush c = new WechatAppAutoPush();
            c = c.getContent(result);
            return c;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
